package com.weixin.portalweb.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: Jack
 * @create: 2019-11-26 10:14
 **/
@Slf4j
@ControllerAdvice
public class WebExceptionHandler {

    @ExceptionHandler(value =NoHandlerFoundException.class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    @ResponseBody
    public ResponseEntity<ErrorResult> handle404(NoHandlerFoundException e) {

        log.info("Resource Not found, RequestURL: {}, HttpMethod: {}, Headers: {}", e.getRequestURL(),
                e.getHttpMethod(), e.getHeaders());
        log.error(e.getMessage(), e);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        ErrorResult errorResult = new ErrorResult();
        errorResult.setCode(WebExceptionCode.NOT_FOUND);
        return new ResponseEntity<>(errorResult, headers, HttpStatus.NOT_FOUND);
    }

    public static final String ERROR_VIEW = "my_error";

    @ExceptionHandler(value = Exception.class)//指定拦截的异常
    public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception{
        e.printStackTrace();//打印异常信息
        ModelAndView mv = new ModelAndView();
        mv.addObject("exception",e);
        mv.addObject("url",request.getRequestURL());//发生异常的路径
        mv.setViewName(ERROR_VIEW);//指定发生异常之后跳转页面
        return mv;
    }
 }
